/**
 *  File: BaseBaoFuService.java
 *  Date         Author      Changes
 *  2016-10-2    wangtq       Create
 *
 */
package com.kunpu.mami.channel.service;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.kunpu.mami.channel.common.BankErrorEnum;
import com.kunpu.mami.channel.common.ResConstants;
import com.kunpu.mami.channel.exception.MamiiException;
import com.kunpu.mami.channel.utils.JacksonUtil;
import com.kunpu.mami.channel.utils.SecurityUtil;
import com.kunpu.mami.channel.utils.http.HttpRequestUtil;
import com.kunpu.mami.channel.utils.rsa.RsaCodingUtil;

/**
 * 发送宝付短信、支付、绑卡基础
 * @author wangtq
 * @date 2016-10-10
 * @version 0.1
 *
 */
public class BaseSendService {

	private static final Logger logger = LoggerFactory.getLogger(BaseSendService.class);

	@Value("${keyPath}")
	public String keyPath  ;//商户私钥
	public  String keyPwd ="123456";// 商户私钥密码
	@Value("${cerPath}")
	public  String cerPath ;//宝付公钥

	// 发送请求
	@Value("${requestUrl}")
	String requestUrl ;
	@Value("${repay_terminal_id}")
	String repay_terminal_id;
	
	@Value("${member_id}")
	String member_id ;
	@Value("${terminal_id}")
	String terminal_id ;
	
	@Value("${domain}")
	public  String domain;
	

	
	//================================
/*	 String member_id = "100000178";
	 String terminal_id = "100000859";
	public  String domain = "https://tgw.baofoo.com/cutpayment/api/backTransRequest";*/

//	final String terminal_id = "30154";
//	public static String domain = "https://public.baofoo.com/cutpayment/api/backTransRequest";



	// ==Ming=====================================
	final String version = "4.0.0.1";
	final String txn_type = "0431";// 交易类型
	final String data_type = "json";
	// ==Mi=======================================
	String id_card_type="01";

	// =================================================================================================================
	/**
	 * 发送报文
	 * 
	 * @param data_content
	 */
	public Map<String,String> send(String data_content,String orignSource,String txn_sub_type) {
		//String txn_sub_type = "05";// 交易子类
		logger.info("============================= 请求宝付 start =======================>,\n 来源{} ,入参为:{}",orignSource,data_content);
		String responseStrDecode = "";
		try {
			// 商户私钥加密。先base64 加密，然后 RSA私钥加密
			data_content = RsaCodingUtil.encryptByPriPfxFile(SecurityUtil.Base64Encode(data_content), keyPath, keyPwd);
			logger.info("------------发送宝付加密后报文:{}",data_content);
			String params = "version=%s&member_id=%s&terminal_id=%s&txn_type=%s&txn_sub_type=%s&data_type=%s&data_content=%s";
			params = String.format(params, version, member_id, terminal_id, txn_type, txn_sub_type, data_type, data_content);
			// ================ POST 提交 =====================
			logger.info("---------[发送宝付请求地址和参数]:"+domain+"?"+params);
			String responseStr = HttpRequestUtil.sendHttpsPost(domain, params, "UTF-8").toString();
			// ================ POST 提交 =====================
			logger.info("---------宝付返回报文:{}",responseStr);
			// 宝付回复密文。。先公钥解密，后base64解密
			responseStr = RsaCodingUtil.decryptByPubCerFile(responseStr, cerPath);
			responseStrDecode = SecurityUtil.Base64Decode(responseStr);
			logger.info("---------解密宝付返回报文:{}",responseStrDecode);
		} catch (Exception e) {
			logger.error("====================================发送宝付失败 :\n",e.getMessage(),e);
			throw new MamiiException(ResConstants.PAY_ANALYSIS_EXISTENT.getCode(), ResConstants.PAY_ANALYSIS_EXISTENT.getMsg());
		}

		Map map = JacksonUtil.json2Map(responseStrDecode);		
		logger.info("---------请求宝付成功，转换后内容为:{}",map);
		if(!map.get("resp_code").equals("0000")) {
			logger.info("---------请求宝付成功，处理返回不为0000业务:");	
			if(map.get("resp_code").equals("BF00103")){
				//提现余额不足
				throw new MamiiException(ResConstants.PAY_RESULT_BALANCE_EXCEPTION.getCode() ,ResConstants.PAY_RESULT_BALANCE_EXCEPTION.getMsg());
			}else if(map.get("resp_code").equals("BF00105")|| map.get("resp_code").equals("BF00106")
					|| map.get("resp_code").equals("BF00132 ")|| map.get("resp_code").equals("BF00133")||
					map.get("resp_code").equals("BF00257")){
				//提现短信验证码不正确
				throw new MamiiException(ResConstants.PAY_RESULT_SENDMSG_EXCEPTION.getCode() ,ResConstants.PAY_RESULT_SENDMSG_EXCEPTION.getMsg());
			}
			String msg = getMsgByCode(map.get("resp_code").toString());
			if(specilException(map.get("resp_code").toString()))
				msg = map.get("resp_msg").toString();
			throw new MamiiException(ResConstants.PAY_RESULT_EXCEPTION.getCode() ,msg);
		}
		logger.info("=========================请求宝付 end ========================");
		return map;
	}

	
	private String getMsgByCode(String code) {
		//ConcurrentHashMap<String ,String> bankCodeMap = BankErrorCodeAcept.ERROR_CODE_MAP;
		String msg =  BankErrorEnum.geteMsgByCode(code);
		if (StringUtils.isBlank(msg)) {
			msg = "交易失败";
		}
		return msg;
	}

	private boolean specilException(String code) {
			String[] codes = {"BF08701" , "BF08702"};
			for(String s : codes) {
				if(s.equals(code))
					return true;
			}
		return false;
	}

	
	
	
	
	public String getRequestUrl() {
		return requestUrl;
	}

	public void setRequestUrl(String requestUrl) {
		this.requestUrl = requestUrl;
	}

	public String getRepay_terminal_id() {
		return repay_terminal_id;
	}

	public void setRepay_terminal_id(String repay_terminal_id) {
		this.repay_terminal_id = repay_terminal_id;
	}

	public String getMember_id() {
		return member_id;
	}

	public void setMember_id(String member_id) {
		this.member_id = member_id;
	}

	public String getTerminal_id() {
		return terminal_id;
	}

	public void setTerminal_id(String terminal_id) {
		this.terminal_id = terminal_id;
	}

	public String getDomain() {
		return domain;
	}

	public void setDomain(String domain) {
		this.domain = domain;
	}

	public String getKeyPath() {
		return keyPath;
	}

	/*public void setKeyPath(String keyPath) {

		this.keyPath = BF0040001Service.class.getResource("/").getPath()+keyPath;
	}*/

	public String getCerPath() {
		return cerPath;
	}

	/*public void setCerPath(String cerPath) {
		this.cerPath =  BF0040001Service.class.getResource("/").getPath()+cerPath;
	}
*/



	
}
